from django.shortcuts import render, redirect
from webapp.models import Mobile
from webapp.modelforms.mymodelform import MobileEdModelForm, MobileModelForm
from webapp.uitls.pagination import Pagination


def mobile_list(request):
    # 添加测试数据
    # for i in range(0, 600):
    #     Mobile.objects.create(mobile="13402046949",price=1000, level=1, status=0)

    # 定义一个集合用来存储查询条件
    data_dict = {}
    # 获取前端传值
    value = request.GET.get("q")
    # 如果q有值，填充条件到集合中。
    if value:
        data_dict["mobile__contains"] = value
    # 封装后的分页逻辑
    page = Pagination(request, Mobile.objects.filter(**data_dict))
    # 根据
    data = Mobile.objects.filter(**data_dict)[page.start_number:page.end_number]
    return render(request, "mobile_list.html", {"data": data, "page_list": page.page_list})


def mobile_add(request):
    if request.method == "GET":
        form = MobileModelForm()
        return render(request, "mobile_add.html", {"form": form})
    form = MobileModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/mobile/list/")
    return render(request, "mobile_add.html", {"form": form})


def mobile_delete(request, nid):
    Mobile.objects.filter(id=nid).delete()
    return redirect("/mobile/list/")


def mobile_edit(request, nid):
    mobile = Mobile.objects.filter(id=nid).first()
    if request.method == "GET":
        form = MobileEdModelForm(instance=mobile)
        return render(request, "mobile_edit.html", {"form": form})
    form = MobileEdModelForm(data=request.POST, instance=mobile)
    if form.is_valid():
        form.save()
        return redirect("/mobile/list/")
    return render(request, "mobile_edit.html", {"form": form})
